package com.miukoo.aikao.admin.security;

import com.miukoo.aikao.metadata.pojos.SysUser;
import com.miukoo.aikao.metadata.service.SysUserRoleService;
import com.miukoo.aikao.metadata.service.SysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author miukoo<miukoo@126.com>
 * @Date 2020/11/20  
 * @Version 1.0
 */
@Component
public class SysUserDetailsService implements UserDetailsService {

    @Autowired
    SysUserService sysUserService;

    @Autowired
    SysUserRoleService sysUserRoleService;

    @Override
    public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException {
        SysUser sysUser = sysUserService.findByName(userName);
        if(sysUser!=null){
            List<GrantedAuthority> list = getUserRole(sysUser.getId());
            return new SecurityUserDto(sysUser.getId(),userName,sysUser.getPassword(),list);
        }
        return null;
    }

    public List<GrantedAuthority> getUserRole(Long userId){
        List<String> roles = sysUserRoleService.listRoles(userId);
        List<GrantedAuthority> list = new ArrayList<>();
        // 后台系统用户角色
        list.add(new SimpleGrantedAuthority("ROLE_ADMIN_USER"));
        if(roles!=null){
            roles.forEach(roleId->{
                list.add(new SimpleGrantedAuthority(roleId));
            });
        }
        return list;
    }
}
